package cn.ailanyin.home.common.advice;

import cn.ailanyin.home.common.entity.Result;
import cn.ailanyin.home.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;
import java.util.Objects;

/**
 * 全局异常处理
 *
 * @author ailanyin
 * @date 2023-09-03 18:44:33
 */
@ControllerAdvice
@Slf4j
public class ExceptionAdvice {

    /**
     * 非自定义异常, 控制台打印错误信息
     *
     * @param e Exception
     * @return Result
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result error(Exception e) {
        e.printStackTrace();
        return Result.error(e.getMessage());
    }

    /**
     * 自定义异常
     *
     * @param e ServiceException
     * @return Result
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Result handlerServiceException(ServiceException e) {
        log.error(e.getMessage());
        return Objects.isNull(e.getErrorCode()) ? Result.error(e.getMessage()) : Result.error(e.getErrorCode(), e.getMessage());
    }

    /**
     * 参数校验
     *
     * @param e MethodArgumentNotValidException
     * @return Result
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public Result handlerValidException(MethodArgumentNotValidException e) {
        return Result.error(Objects.isNull(e.getBindingResult().getFieldError()) ? e.getMessage() : e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 参数校验
     *
     * @param e BindException
     * @return Result
     */
    @ExceptionHandler({BindException.class})
    @ResponseBody
    public Result handlerValidException(BindException e) {
        return Result.error(Objects.isNull(e.getBindingResult().getFieldError()) ? e.getMessage() : e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 参数校验
     *
     * @param e ConstraintViolationException
     * @return Result
     */
    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseBody
    public Result handlerValidException(ConstraintViolationException e) {
        return Result.error(e.getMessage());
    }

}
